package com.mailbox.mailbox.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mailbox.mailbox.domain.*;
import com.mailbox.mailbox.domain.responsePojo.ReturnMessage;
import com.mailbox.mailbox.domain.responsePojo.ReturnReply;
import com.mailbox.mailbox.mapper.*;
import com.mailbox.mailbox.service.ReceptionService;
import com.mailbox.mailbox.util.CommenUtils;
import com.mailbox.mailbox.util.ResponseResult;
import com.mailbox.mailbox.util.SendEmail.SendEmailUtil;
import com.mailbox.mailbox.util.SendEmail.VerCodeGenerateUtil;
import lombok.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.nio.cs.US_ASCII;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 张铭辉
 */
@Service
public class ReceptionServiceImpl extends ServiceImpl<ReceptionMapper, Message> implements ReceptionService {

    @Resource
    HttpServletRequest request;
    @Resource
    IpMapper ipMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    ReceptionMapper receptionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addAMessage(@NonNull Message message) {
        if (message.getTouristName()!=null){
            String regex1 = "[\\u4E00-\\u9FA5]+";
            boolean matches1 = message.getTouristName().matches(regex1);
            if (!matches1 || message.getTouristName().length()>20){
                return ResponseResult.error("姓名格式错误");
            }
        }
        if (message.getTouristPhone()!=null){
            String regex2="[^(0-9)]";
            Matcher matcher2= Pattern.compile(regex2).matcher(message.getTouristPhone());
            if (matcher2.find() || message.getTouristPhone().length()!=11){
                return ResponseResult.error("电话格式错误");
            }
        }
        if (message.getTouristEmail()!=null){
            String regex3="^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$";
            boolean matches3 = message.getTouristEmail().matches(regex3);
            if(!matches3 || message.getTouristEmail().length()>25){
                return ResponseResult.error("电子邮箱格式错误");
            }
        }
        if (message.getMessageContent()==null){
            return ResponseResult.error("内容不能为空");
        }
        if (message.getMessageTitle()==null){
            return ResponseResult.error("标题不能为空");
        }
        if (message.getMessageType()==null){
            return ResponseResult.error("类型不能为空");
        }
        String ip=CommenUtils.getIpAddress(request);
        Boolean b=CommenUtils.verifyIp(ip,ipMapper);
        if(!b){
            return ResponseResult.error("今日次数上线,请明日再来");
        }
        if (message.getTouristName()==null){
            return ResponseResult.error("姓名不能为空");
        }
        if (message.getTouristPhone()==null){
            return ResponseResult.error("电话不能为空");
        }
        if (message.getTouristEmail()==null){
            return ResponseResult.error("邮箱不能为空");
        }
        message.setMessageId(null);
        message.setIsReply(0);
        LocalDateTime localDateTime=LocalDateTime.now();
        message.setCreateTime(Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant()));
        message.setIsDelete(0);
        message.setIsReply(0);
        int insert = this.baseMapper.insert(message);

        if (insert != 0){
            return ResponseResult.success("留言成功");
        }else {
            return ResponseResult.error("留言失败");
        }
    }

    @Override
    public ResponseResult findAllTypes() {
        List<Type> types = this.baseMapper.findAllTypes();
        if (types!=null){
            return ResponseResult.success(types);
        }else {
            return ResponseResult.error("系统错误");
        }
    }

    @Override
    public ResponseResult judgeEmail(@NonNull String email,@NonNull String flag) {
        if(flag.equals("@163.com")){
            if(!VerCodeGenerateUtil.emailRegular(email,"@163.com")){
                return ResponseResult.error("失败，请检查邮箱格式是否正确");
            }
        }else if(flag.equals("@qq.com")) {
            if (!VerCodeGenerateUtil.emailRegular(email, "@qq.com")) {
                return ResponseResult.error("失败，请检查邮箱格式是否正确");
            }
        }else {
            return ResponseResult.error("抱歉，暂不支持此类邮箱");
        }
        String code = VerCodeGenerateUtil.generateVerCode();
        SendEmailUtil.sendEmail(code,email+flag,flag);
        return ResponseResult.success("您本次的验证码为："+code+",验证码五分钟内有效，请勿泄露给他人");
    }

    @Override
    public ResponseResult findAllMessages(@NonNull Integer page,@NonNull Integer size,@NonNull Integer id) {
        User user=userMapper.selectById(id);
        if(user==null){ return ResponseResult.error("用户不存在");}
        PageHelper.startPage(page,size);
        List<ReturnMessage> allMessages = this.baseMapper.findAllMessages(user.getPhoneNumber());
        PageInfo<ReturnMessage> pageInfo=new PageInfo<>(allMessages);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findSuchMessages(Integer page, Integer size, String messageType, String startTime, String endTime,@NonNull Integer userId) {
        User user = userMapper.selectById(userId);
        if(user==null){ return ResponseResult.error("用户不存在");}
        List<ReturnMessage> list;
        if (messageType!=null){
            if (startTime!=null && endTime!=null){
                list = this.baseMapper.findSuchMessage(startTime, endTime, messageType,user.getPhoneNumber());
            }else {
                list = this.baseMapper.findSuchMessageType(messageType,user.getPhoneNumber());
            }
        }else {
            if (startTime!=null && endTime!=null){
                list = this.baseMapper.findSuchMessageTime(startTime, endTime,user.getPhoneNumber());
            }else {
                list = this.baseMapper.findAllMessages(user.getPhoneNumber());
            }
        }
        PageHelper.startPage(page,size);
        PageInfo<ReturnMessage> pageInfo=new PageInfo<>(list);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findOpenMessages(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<ReturnMessage> replyList= receptionMapper.findAllOpenMessages();
        PageInfo<ReturnMessage> pageInfo=new PageInfo<>(replyList);
        return ResponseResult.success("查询成功",pageInfo);
    }

}